package com.yuandian.middle.platform.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * .txt 文件生成器
 */
@Service
@Slf4j
public class TextFileGenerator {

//	@Transactional
	public static void generateTextFile(String filePath, List<String> lines) {
		generateTextFile(filePath, lines, false);
	}

//	@Transactional
	public static void generateTextFile(String filePath, List<String> lines, boolean append) {

		File file = new File(filePath);
		file.setWritable(true, false);
		if(!file.getParentFile().exists()) {
			file.getParentFile().mkdirs();
			String command = "chmod -R 777" + filePath;
			log.info("本地文件夹不存在，重新创建授权: " + command);
			try {
				Runtime.getRuntime().exec(command);
			} catch (Exception e) {

				log.error("文件授权异常 " + command);
				throw new RuntimeException("文件授权异常 " + command);
			}
		}

		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(filePath, append));
			for (String line : lines) {
				writer.write(line);
				writer.newLine();  // 换行
			}
			log.info("文件生成成功: {}", filePath);
		} catch (IOException e) {
			log.error("文件生成失败: {}", e.getMessage());
			e.printStackTrace();
			throw new RuntimeException("文件生成失败: " + e.getMessage(), e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					log.error("Error closing writer: {}", e.getMessage());
					e.printStackTrace();
				}
			}
		}
	}

	public static void main(String[] args) {
		String filePath = "D:\\" + System.currentTimeMillis() + ".txt";
		// 准备多行数据
		List<String> lines = new ArrayList<>();
		lines.add("Line 1€€");
		lines.add("Line 2€€");
		lines.add("Line 3€€");
		generateTextFile(filePath, lines);
	}
}
